import networkx as nx
import numpy as np
from scipy import sparse

from EmpVoting import NetworkModifier

class AgentWeightGlobalAlg(NetworkModifier):

    def __init__(self, useDynamicFields = False):
        '''
        Constructor
        '''
        self.useDynamicFields = useDynamicFields
        
    def Apply(self, network):
        numAgents = len(network.agentList)
        
        #adjacencyMatrix
        M = nx.to_scipy_sparse_matrix(network.graph)
        #selfLoopMatrix
        D = sparse.tril(M) - sparse.tril(M, -1)
        I = sparse.identity(numAgents)
        eT = np.ones((1, numAgents))
        
        #w^T = e^T (I - M + D)^(-1) D
        omega = eT * (I - M + D).todense().I * D
        
        omegaIndex = 0
        for node in network.graph.nodes_iter():
            self.SetAgentField(node, "weight", float(omega[0, omegaIndex]))
            omegaIndex += 1
            
        #omega = sparse.linalg.spsolve(invMatrix, D)
